package cn.ewan.cloud.tenant.data.router.core.business.context;

import cn.ewan.cloud.common.web.support.BusinessException;
import cn.ewan.cloud.tenant.data.router.core.business.config.tenant.TenantUser;
import cn.ewan.cloud.tenant.data.router.core.common.exception.TenantMsgCode;
import com.alibaba.ttl.TransmittableThreadLocal;
import org.apache.commons.lang3.StringUtils;

/**
 * @author lgh
 * @date 2022/12/19 15:43
 */
public class TenantContext {

    private static final TransmittableThreadLocal<TenantUser> TENANT_USER = new TransmittableThreadLocal<>();


    /**
     * 获取租户标识
     *
     * @return 标识
     */
    public static String getTenant() {
        String tenant = getTenantNoCheck();
        if (StringUtils.isBlank(tenant)) {
            throw new BusinessException(TenantMsgCode.TENANT_FLAG_NO_EXIST);
        }
        return tenant;
    }


    public static String getTenantNoCheck() {
        return getTenantUser().getTenant();
    }

    /**
     * 设置租户
     *
     * @param tenant 标识
     */
    public static void setTenant(String tenant) {
        TenantUser tenantUser = getTenantUser();
        tenantUser.setTenant(tenant);
        TENANT_USER.set(tenantUser);
    }


    /**
     * 查询租户信息
     *
     * @return 租户信息
     */
    public static TenantUser getTenantUser() {
        return TENANT_USER.get() != null ? TENANT_USER.get() : new TenantUser();
    }


    /**
     * 移除
     */
    public static void removeTenant() {
        TENANT_USER.remove();
    }
}
